package com.lottery.im.module.chat.ui;

import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.OnClick;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.fondesa.recyclerviewdivider.RecyclerViewDivider;
import com.lottery.im.R;
import com.lottery.im.base.BaseSwipeFragment;
import com.lottery.im.module.contact.adapter.GroupListAdapter;
import com.lottery.im.module.tim.model.GroupInfo;
import com.lottery.im.module.tim.model.GroupProfile;
import com.lottery.im.module.tim.model.SectionGroupProfile;
import java.util.ArrayList;
import java.util.List;

/**
 * 创建群聊 选择群
 */
public class CreateGroupGroupFragment extends BaseSwipeFragment {

  @BindView(R.id.tv_title) TextView mTvTitle;
  @BindView(R.id.tv_empty) TextView mTvEmpty;
  @BindView(R.id.list) RecyclerView mList;

  private List<SectionGroupProfile> mSectionGroupProfiles;
  private GroupListAdapter mAdapter;

  @Override protected int getLayoutResId() {
    return R.layout.fragment_group_list;
  }

  @Override protected void initPresenter() {
    initView();
  }

  private void initView() {

    mTvTitle.setText("创建群聊");
    mSectionGroupProfiles = new ArrayList<>();
    mList.setLayoutManager(new LinearLayoutManager(getActivity()));

    RecyclerViewDivider.with(mActivity)
        .color(ContextCompat.getColor(mActivity, R.color.windowBackground))
        .size((int) mActivity.getResources().getDimension(R.dimen.line_size))
        .hideLastDivider()
        .build()
        .addTo(mList);

    mAdapter = new GroupListAdapter(mSectionGroupProfiles);
    mAdapter.setOnItemClickListener((adapter, view, position) -> {

      GroupProfile groupProfile = mSectionGroupProfiles.get(position).t;
      if (null != groupProfile) {
        startFragmentAndDestroyCurrent(
            CreateGroupMemberFragment.create(groupProfile.getIdentify()));
      }
    });
    mList.setAdapter(mAdapter);
    setUI();
  }

  private void setUI() {
    mSectionGroupProfiles.clear();

    List<GroupProfile> list = GroupInfo.getInstance().getGroupListByType(GroupInfo.publicGroup);
    for (GroupProfile summary : list) {
      SectionGroupProfile sectionProfile = new SectionGroupProfile(summary);
      mSectionGroupProfiles.add(sectionProfile);
    }
    if (mSectionGroupProfiles.size() > 0) {
      mAdapter.notifyDataSetChanged();
      mTvEmpty.setVisibility(View.GONE);
      mList.setVisibility(View.VISIBLE);
    } else {
      mTvEmpty.setVisibility(View.VISIBLE);
      mList.setVisibility(View.GONE);
    }
  }

  @OnClick(R.id.iv_back) public void onViewClicked() {
    popBackStack();
  }
}
